package com.wyp.didishige.activity.me;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadBatchListener;
import com.bmob.btp.callback.UploadListener;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.wyp.didishige.utils.ImageLoaderUtil;
import com.wyp.didishige.utils.OperationUtils;
import com.wyp.didishige.utils.PhotoUtil;
import com.wyp.didishige.R;
import com.wyp.didishige.activity.BaseActivity;
import com.wyp.didishige.activity.PoiSearchActivity;
import com.wyp.didishige.adapter.UserSetImageGridAdapter;
import com.wyp.didishige.config.BmobConstants;
import com.wyp.didishige.model.User;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.utils.ToastUtil;
import com.wyp.didishige.wiget.ScrollNestGridView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 用户编辑个人信息
 */
public class UserEditActivity extends BaseActivity implements View.OnClickListener {
    /**
     * 选择设置小区
     */
    private static final int SET_COMMUNITY_CODE = 0;

    /**
     * 用户昵称
     */
    private AppCompatEditText user_nick;
    /**签名*/
    /**
     * 几幢
     */
    private AppCompatEditText user_build;
    /**
     * 房号
     */
    private AppCompatEditText user_house;
    /**
     * 生活圈
     */
    private AppCompatEditText user_lifeCircle;
    /**
     * 工作圈
     */
    private AppCompatEditText user_workCircle;
    /**
     * 家乡
     */
    private AppCompatEditText user_hometown;
    /**
     * 兴趣爱好
     */
    private AppCompatEditText user_interest;

    private AppCompatEditText user_sign;
    /**
     * 出生日期
     */
    private TextView user_birthday;
    /**
     * 小区
     */
    private TextView user_community;
    /**
     * 生日区域
     */
    private LinearLayout lay_birthDay;
    /**
     * 选择小区区域
     */
    private LinearLayout lay_user_community;
    /**
     * 当前登录用户
     */
    private User loginUser = null;
    /**
     * 添加图片
     */
    ImageView add_image;
    /**
     * 添加照片
     */
    ScrollNestGridView gridview_image=null;

    private RelativeLayout layout_image;

    UserSetImageGridAdapter girdAdapter;

    /**
     * 新增图片列表
     */
    ArrayList<String> hasList = new ArrayList<String>();
    ArrayList<BitmapDrawable> bitMapHasList = new ArrayList<BitmapDrawable>();
    boolean isFromCamera = false;// 区分拍照旋转
    int degree = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_edit);
        actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("编辑资料");
        try {
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取用户信息
     */
    private void initUser() {
        BmobQuery<User> query = new BmobQuery<User>();
        query.getObject(this, loginUser.getObjectId(), new GetListener<User>() {
            @Override
            public void onSuccess(User us) {
                if (us == null) {
                    finish();
                }
                loginUser = us;
                setWidget();
            }

            @Override
            public void onFailure(int i, String s) {
                ShowToast("请检测网络设置");
            }
        });
    }
    @Override
    protected void initParamter() {
        super.initParamter();
        loading.setCancelable(true);
        loginUser = userManager.getCurrentUser(User.class);
        girdAdapter = new UserSetImageGridAdapter(this, imageList);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        gridview_image= (ScrollNestGridView) findViewById(R.id.add_image_gridView);

        user_nick = (AppCompatEditText) findViewById(R.id.user_name);
        user_birthday = (TextView) findViewById(R.id.user_birthday);
        user_sign = (AppCompatEditText) findViewById(R.id.user_sign);
        user_community = (TextView) findViewById(R.id.user_community);
        user_build = (AppCompatEditText) findViewById(R.id.user_build);
        user_house = (AppCompatEditText) findViewById(R.id.user_house);
        user_lifeCircle = (AppCompatEditText) findViewById(R.id.user_lifeCircle);
        user_workCircle = (AppCompatEditText) findViewById(R.id.user_workCircle);
        user_hometown = (AppCompatEditText) findViewById(R.id.user_hometown);
        user_interest = (AppCompatEditText) findViewById(R.id.user_interest);
        lay_birthDay = (LinearLayout) findViewById(R.id.lay_birthDay);
        lay_user_community = (LinearLayout) findViewById(R.id.lay_user_community);
        layout_all = (ScrollView) findViewById(R.id.layout_all);
        add_image = (ImageView) findViewById(R.id.add_image);
        layout_image = (RelativeLayout) findViewById(R.id.layout_image);
    }

    @Override
    protected void initWidgetListener() {
        super.initWidgetListener();
        lay_birthDay.setOnClickListener(this);
        lay_user_community.setOnClickListener(this);
        add_image.setOnClickListener(this);

        gridview_image.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object object = parent.getAdapter().getItem(position);
                operate(object);
            }
        });
        gridview_image.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Object object = parent.getAdapter().getItem(position);
                setAvator(object);
                return true;
            }
        });
        user_interest.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                loginUser.setUserInterest(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        user_hometown.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                loginUser.setUserHometown(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        user_workCircle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                loginUser.setWorkCircle(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        user_lifeCircle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                loginUser.setLifeCircle(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        user_house.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                loginUser.setHouse(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        user_build.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                loginUser.setBuild(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        user_sign.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                loginUser.setUserSign(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        user_nick.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                loginUser.setNick(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 删除图片
     * @param object
     */
    private void operate(final Object object){
        AlertDialog.Builder build=new AlertDialog.Builder(this);
        build.setMessage("是否删除图片");
        build.setTitle("提示");
        build.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        build.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (object instanceof String) {
                    hasList.remove(object);
                } else {
                    BmobFile file = (BmobFile) object;
                    loginUser.getAvatars().remove(file);
                }
                girdAdapter.remove(object);
                dialog.cancel();
            }
        });
        build.show();
    }

    /**
     * 设置头像
     * @param object
     */
    private void setAvator(final Object object){
        AlertDialog.Builder build=new AlertDialog.Builder(this);
        build.setMessage("是否设置为头像");
        build.setTitle("提示");
        build.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        build.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (object instanceof String){
                    String url= (String) object;
                    updateAvator(url);
                    layout_image.setBackground(new BitmapDrawable(url));
                }else{
                    BmobFile file = (BmobFile) object;
                    loginUser.setAvatar(file.getUrl());
                    setBg(file.getUrl());
                }
                dialog.cancel();
            }
        });
        build.show();
    }

    private void setBg(String url){
        ImageLoaderUtil.ImageLoaderInstance.loadImage(url, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {

            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                layout_image.setBackground(new BitmapDrawable(bitmap));
            }

            @Override
            public void onLoadingCancelled(String s, View view) {

            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_birthDay:
                setBirthDay();
                break;
            case R.id.lay_user_community:
                Bundle bundle = new Bundle();
                bundle.putString(PoiSearchActivity.ADDRESS, "");
                IntentUtil.start_activity_for_result(UserEditActivity.this, PoiSearchActivity.class, SET_COMMUNITY_CODE, bundle);
                break;
            case R.id.add_image:
                showAvatarPop();
                break;
        }
    }

    @Override
    protected void initWidgetState() {
        super.initWidgetState();
        initUser();
    }

    private void setWidget(){
        if (loginUser != null) {
            setBg(loginUser.getAvatar());
            user_nick.setText(loginUser.getNick());
            user_birthday.setText(loginUser.getUserBirthday());
            user_sign.setText(loginUser.getUserSign());
            user_community.setText(loginUser.getCommunity());
            user_build.setText(loginUser.getBuild());
            user_house.setText(loginUser.getHouse());
            user_lifeCircle.setText(loginUser.getLifeCircle());
            user_workCircle.setText(loginUser.getWorkCircle());
            user_hometown.setText(loginUser.getWorkCircle());
            user_interest.setText(loginUser.getUserInterest());
        }
        gridview_image.setAdapter(girdAdapter);
        getUserImage();
    }

    /**
     * 设置生日
     */
    private void setBirthDay() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                loginUser.setUserBirthday(year + "-" + (monthOfYear+1) + "-" + dayOfMonth);
                user_birthday.setText(loginUser.getUserBirthday());
            }
        }, 1990, 0, 1);
        datePickerDialog.show();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            try {
                switch (requestCode){
                    case SET_COMMUNITY_CODE:
                        if (data!=null && data.getExtras()!=null){
                            String address = data.getExtras().getString(PoiSearchActivity.ADDRESS);
                            user_community.setText(address);
                            loginUser.setCommunity(address);
                        }
                        break;
                    case BmobConstants.REQUESTCODE_UPLOADAVATAR_CAMERA:// 拍照修改头像
                            if (!Environment.getExternalStorageState().equals(
                                    Environment.MEDIA_MOUNTED)) {
                                ShowToast("SD不可用");
                                return;
                            }

                            isFromCamera = true;
                            File file = new File(filePath);
                            degree = PhotoUtil.readPictureDegree(file.getAbsolutePath());
                            Log.i("life", "拍照后的角度：" + degree);
                            OperationUtils.startImageAction(UserEditActivity.this, Uri.fromFile(file), 200, 200,
                                    BmobConstants.REQUESTCODE_UPLOADAVATAR_CROP, true);
                        break;
                    case BmobConstants.REQUESTCODE_UPLOADAVATAR_LOCATION:// 本地修改头像
                        if (avatorPop != null) {
                            avatorPop.dismiss();
                        }
                        Uri uri = null;
                        if (data == null) {
                            return;
                        }
                            if (!Environment.getExternalStorageState().equals(
                                    Environment.MEDIA_MOUNTED)) {
                                ShowToast("SD不可用");
                                return;
                            }
                            isFromCamera = false;
                            uri = data.getData();
                            String uriPath =  uri.getPath();
                            OperationUtils.startImageAction(UserEditActivity.this, uri, 200, 200,
                                    BmobConstants.REQUESTCODE_UPLOADAVATAR_CROP, true);
                        break;
                    case BmobConstants.REQUESTCODE_UPLOADAVATAR_CROP:// 裁剪头像返回
                        if (avatorPop != null) {
                            avatorPop.dismiss();
                        }
                        if (data == null) {
                            // Toast.makeText(this, "取消选择", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            saveCropAvator(data);
                        }
                        // 初始化文件路径
                        filePath = "";
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 保存裁剪的头像
     *
     * @param data
     */
    private void saveCropAvator(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap bitmap = extras.getParcelable("data");
            Log.i("life", "avatar - bitmap = " + bitmap);
            if (bitmap != null) {
                bitmap = PhotoUtil.toRoundCorner(bitmap, 10);
                if (isFromCamera && degree != 0) {
                    bitmap = PhotoUtil.rotaingImageView(degree, bitmap);
                }
                // 保存图片
                String filename = new SimpleDateFormat("yyMMddHHmmss")
                        .format(new Date()) + ".png";

                PhotoUtil.saveBitmap(BmobConstants.MyAvatarDir, filename,
                        bitmap, true);
                String imagePath="";
                imagePath += BmobConstants.MyAvatarDir + filename;
                hasList.add(imagePath);
                girdAdapter.addPhotoImage(imagePath);

                // 上传头像
                if (bitmap != null && bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            }
        }
    }

    private void uploadImage(){
        String[] files = new String[hasList.size()];
        for (int i=0;i<hasList.size();i++){
            files[i] = hasList.get(i);
        }
        loading.setTitle("提示");
        loading.setMessage("努力保存ING");
        loading.setIndeterminate(false);
        loading.show();

        if (files.length == 0){
            update();
            return;
        }

        BmobProFile.getInstance(this).uploadBatch(files, new UploadBatchListener() {
            @Override
            public void onSuccess(boolean isFinish, String[] strings, String[] strings1, BmobFile[] bmobFiles) {
                if (isFinish) {
                    List<BmobFile> ava = loginUser.getAvatars();
                    if (ava==null){
                        ava=new ArrayList<BmobFile>();
                    }

                    for (BmobFile file :
                            bmobFiles) {
                        ava.add(file);
                    }

                    loginUser.setAvatars(ava);
                    update();
                }

            }

            @Override
            public void onProgress(int i, int i1, int i2, int i3) {
            }

            @Override
            public void onError(int i, String s) {
                loading.cancel();
            }
        });
    }

    /**
     * 更新头像
     * @param url
     */
    private void updateAvator(String url){
        loading.setMessage("更新头像");
        loading.show();
        BmobProFile.getInstance(this).upload(url, new UploadListener() {
            @Override
            public void onSuccess(String s, String s1, BmobFile bmobFile) {
                loginUser.setAvatar(bmobFile.getUrl());
            }

            @Override
            public void onProgress(int i) {
                if (i==100){
                    loading.cancel();
                }
            }

            @Override
            public void onError(int i, String s) {
                loading.cancel();
            }
        });
    }
    /**
     * 更新信息
     */
    private void update() {
        loginUser.update(this, new UpdateListener() {
            @Override
            public void onSuccess() {
                loading.cancel();
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onFailure(int i, String s) {
                loading.cancel();
                ToastUtil.showShort(UserEditActivity.this, "更新失败，请稍候重试");
            }
        });
    }
    /**
     * 相册
     */
    protected List<Object> imageList=new ArrayList<Object>();
    /**
     * 获取用户展示图片
     */
    private void getUserImage() {
        if (loginUser.getAvatars()!=null){
            for (BmobFile file:loginUser.getAvatars()){
                imageList.add(file);
            }
        }
        girdAdapter.notifyDataSetChanged();
    }
    int page = 0;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_user_edit, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                return true;
            case R.id.action_settings:
                uploadImage();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    RelativeLayout layout_choose;
    RelativeLayout layout_photo;
    PopupWindow avatorPop;
    private ScrollView layout_all;
    public String filePath = "";
    private void showAvatarPop() {
        try {
            View view = LayoutInflater.from(this).inflate(R.layout.pop_showavator,
                    null);
            layout_choose = (RelativeLayout) view.findViewById(R.id.layout_choose);
            layout_photo = (RelativeLayout) view.findViewById(R.id.layout_photo);
            layout_photo.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    layout_choose.setBackgroundColor(getResources().getColor(
                            R.color.base_color_text_white));
                    layout_photo.setBackgroundDrawable(getResources().getDrawable(
                            R.drawable.pop_bg_press));
                    File dir = new File(BmobConstants.MyAvatarDir);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    // 原图
                    File file = new File(dir, new SimpleDateFormat("yyMMddHHmmss")
                            .format(new Date()));
                    filePath = file.getAbsolutePath();// 获取相片的保存路径
                    Uri imageUri = Uri.fromFile(file);

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent,
                            BmobConstants.REQUESTCODE_UPLOADAVATAR_CAMERA);
                }
            });
            layout_choose.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    layout_photo.setBackgroundColor(getResources().getColor(
                            R.color.base_color_text_white));
                    layout_choose.setBackgroundDrawable(getResources().getDrawable(
                            R.drawable.pop_bg_press));
                    Intent intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent,
                            BmobConstants.REQUESTCODE_UPLOADAVATAR_LOCATION);
                }
            });

            avatorPop = new PopupWindow(view, mScreenWidth, 600);
            avatorPop.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        avatorPop.dismiss();
                        return true;
                    }
                    return false;
                }
            });

            avatorPop.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
            avatorPop.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
            avatorPop.setTouchable(true);
            avatorPop.setFocusable(true);
            avatorPop.setOutsideTouchable(true);
            avatorPop.setBackgroundDrawable(new BitmapDrawable());
            // 动画效果 从底部弹起
            avatorPop.setAnimationStyle(R.style.Animations_GrowFromBottom);
            avatorPop.showAtLocation(layout_all, Gravity.BOTTOM, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
